import { Body, Get, Inject, Post, Provide, Query, ALL } from '@midwayjs/decorator';
import { CoolController, BaseController } from '@cool-midway/core';
import { UserInfoEntity } from '../../entity/info';
import { UserInfoService } from '../../service/info';
import { UserFollowService } from '../../service/follow';
import { UserNotifyService } from '../../service/notify';
import { UserActionLogService } from '../../../user/service/log';
import { WeiboBlogService } from '../../../weibo/service/weibo';

/**
 * 用户
 */
@Provide()
@CoolController({
  api: ['update', 'page'],
  insertParam: ctx => {
    return {
      id: ctx.user.id,
    };
  },
  entity: UserInfoEntity
})
export class AppUserInfoController extends BaseController {
  @Inject()
  userInfoService: UserInfoService;

  @Inject()
  userFollowSrv: UserFollowService;

  @Inject()
  weiboBlogSrv: WeiboBlogService;

  @Inject()
  userNotifySrv: UserNotifyService;

  @Inject()
  userActionLogSrv: UserActionLogService;


  @Inject()
  ctx;

  /**
   * 获得个人信息
   * @returns
   */
  @Get('/person')
  async person() {
    const data = await this.userInfoService.personal(this.ctx.user.id)
    // 查询用户ip
    data['ipAddr'] = await this.userActionLogSrv.getUserIpAddr(this.ctx.user.id)
    // 查询用户作品的点赞数
    // const worksList = await this.weiboBlogSrv.page({userId:this.ctx.user.id,size:999, my: 'type'})
    // data['countLoves']=worksList.list.reduce((pre, cur) => {
    //   return pre + cur.count_love;
    // },
    // 0)
    return this.ok(data);
  }

  /**
   * 绑定小程序手机号码
   * @param code
   * @param encryptedData
   * @param iv
   * @returns
   */
  @Post('/bindMiniPhone')
  async bindMiniPhone(@Body() code, @Body() encryptedData, @Body() iv) {
    return this.ok(
      await this.userInfoService.bindMiniPhone(
        code,
        encryptedData,
        iv,
        this.ctx.user.id
      )
    );
  }

  @Get('/follow')
  async follows(@Query() id: any) {
    // 给自己增加关注数量
    let str = await this.userFollowSrv.upCount(
      this.ctx.user.id,
      id,
      'countFollows'
    );

    if (['up', 'cancel'].includes(str)) {
      if (this.ctx.user.id !== id && str == 'up') {
        // 存消息通知
        this.userNotifySrv.save({
          type: 2, //1、公告 2、提醒 3、私信
          action: 4, // 1点赞 2评论 3回复 4关注
          senderId: this.ctx.user.id,
          userId: id,
        });
      }
      return this.ok(str);
    }

    return this.fail(str);
  }

  @Get('/info')
  async info(@Query() sn: string) {
    if (sn) {
      const userInfo = await this.userInfoService.getBySn(sn);
      let is_follow = false;
      let ip_addr = '';
      if (this.ctx.user) {
        is_follow = await this.userFollowSrv.isFollow(
          userInfo.id,
          this.ctx.user.id
        );
        ip_addr = await this.userActionLogSrv.getUserIpAddr(userInfo.id);
      }

      if (userInfo) {
        return this.ok(Object.assign(userInfo, { is_follow, ip_addr }));
      }
      return this.fail('未知错误！');
    }
    return this.fail('参数错误！');
  }

  @Get('/ranking')
  async getRank(@Query(ALL) query: any) {
    let { type = "hot" } = query
    if (type == 'hot') {
      return this.ok(await this.userInfoService.findhotRank(query))
    } else {
      // 找出最近的发帖用户 点赞最高的
      const data = await this.weiboBlogSrv.findHotWeiboList({...query,order:'user_id'})
      console.log(data);
      
      return this.ok(await this.userInfoService.findUserByIds(data, 'user_id'))
    }
  }
}
